package gov.jslt.app.config;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import android.content.Context;

/*******************************************************************************
 * 
 * @author 杨希
 * 
 */
public class BootStrat {

	public static final String GDLT_BOOTSTRAP = "bootstar.properties";

	private static BootStrat applicationContext = null;

	private static Map<Object, Object> contextPool = null;

	private static boolean initialized = false;

	private BootStrat(Context context) {
		init(context);
	}

	public static void reload(Context context) {
		applicationContext = new BootStrat(context);
	}

	private void init(Context context) {
		contextPool = new HashMap<Object, Object>();
		if (BootStrat.initialized) {
			return;
		}
		loadProperties(context);
		this.setInitialized(true);
	}

	private void loadProperties(Context context) {
		Properties props = this.getProperties(context);
		Set<Object> set = props.keySet();
		Iterator<Object> iter = set.iterator();
		while (iter != null && iter.hasNext()) {
			String key = (String) iter.next();
			String value = props.getProperty(key);
			synchronized (contextPool) {
				contextPool.put(key, value);
			}
		}
	}

	private Properties getProperties(Context context) {
		Properties props = new Properties();
		InputStream is = null;
		try {
			is = context.getAssets().open(GDLT_BOOTSTRAP);
			props.load(is);
		} catch (Exception e) {
			props = null;
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (Exception e) {
			}
		}
		return props;
	}

	public static BootStrat singleton(Context context) {
		if (applicationContext == null) {
			applicationContext = new BootStrat(context);
		}
		return applicationContext;
	}

	public void clear() {
		contextPool.clear();
		BootStrat.initialized = false;
	}

	public Object getValue(String key) {
		return contextPool.get(key);
	}

	public void setValue(Object key, Object value) {
		contextPool.put(key, value);
	}

	public String getValueAsString(String key) {
		return (String) this.getValue(key);
	}

	public boolean isInitialized() {
		return BootStrat.initialized;
	}

	private void setInitialized(boolean flag) {
		BootStrat.initialized = flag;
	}

	public void reLoadConfig(Context context) {
		this.clear();
		this.init(context);
	}
}
